<template>
  <div ref="scrolldiv" @scroll="scroll" :style="{height: documentHeight-250 + 'px',width: '100%', overflow:'auto' }">
    <!--    <div style="font-size:12px;height: 40px;width:100%;text-align: center;color: #FFF;line-height: 40px ">-->
    <!--&lt;!&ndash;      在这里配置数据的来源端和写入端；可以是默认的数据源，也可以是您创建的自有数据源<a>查看支持的数据来源类型</a>&ndash;&gt;-->
    <!--    </div>-->
    <div>

      <el-collapse v-model="activeNames">
        <!--       选择数据源-->
        <el-collapse-item name="1">
          <template slot="title">
            <svg-icon
              style="width: 120px;height: 30px"
              icon-class="labelone" />
            <span style="margin-left:18%;color: #fff;">数据来源</span>
            <span style="margin-left:45%;color: #fff;">数据去向</span>
          </template>
          <div style="display: flex; height: 300px; flex-direction:row">
            <div style="width: 50%;">
              <el-form label-width="120px" ref="dataSourceForm" :model="dataSourceForm">
                <el-form-item label="数据源">
                  <el-select filterable style="width: 33%" size="mini" @change="dataSourceChange()"
                             v-model="dataSourceForm.dataSource" placeholder="数据源">
                    <el-option
                      v-for="item in dataSourceOptions"
                      :key="item.id"
                      :label="item.datasourceName"
                      :value="item.id">
                    </el-option>
                  </el-select>
                  <el-select filterable clearable style="width: 32%;margin-left: 5px" v-if="schemasfromtag" size="mini"
                             @change="dataSourceschemaChange()"
                             v-model="dataSourceForm.schema" placeholder="">
                    <el-option
                      v-for="(item,index) in schemasFromOption"
                      :key="index"
                      :label="item.lable"
                      :value="item.lable">
                    </el-option>
                  </el-select>
                  <el-select filterable clearable @change="tableSelectChange('from')"
                             style="width: 33%;margin-left: 5px"
                             ref="tableSelect" size="mini" v-model="dataSourceForm.dataSourceTable"
                             placeholder="选择表">
                    <el-option
                      v-for="(item,index) in tableOptions"
                      :key="index"
                      :label="item.lable"
                      :value="item.lable">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item v-if="!dataSourceForm.dataSourceTable" label="查询sql">
                  <el-input style="width: 82%" type="textarea" :rows="6" size="mini"
                            placeholder="${startId}表示起始值，${endId}表示结束值"
                            v-model="dataSourceForm.srcSqlText"></el-input>
                  <el-button type="primary" style="margin-left: 10px" size="mini" @click="sqlgetfield('tag')">获取字段
                  </el-button>
                </el-form-item>
                <el-form-item v-if="dataSourceForm.dataSourceTable" label="筛选条件">
                  <el-input style="width: 99%" size="mini" placeholder="where条件，不需要再加where"
                            v-model="dataSourceForm.srcWhereParam"></el-input>
                </el-form-item>
                <el-form-item label="增量键表达式">
                  <el-input style="width: 99%" size="mini" placeholder=""
                            v-model="dataSourceForm.srcIdExpression"></el-input>
                </el-form-item>
                <el-form-item label="增量键起始值">
                  <el-input style="width: 99%" size="mini" placeholder="支持使用变量"
                            v-model="dataSourceForm.srcStartId"></el-input>
                </el-form-item>
                <!--               <el-form-item label="增量键偏移量">-->
                <!--               <el-input style="width: 99%" size="mini"  placeholder="" v-model="dataSourceForm.srcIdOffset"></el-input>-->
                <!--             </el-form-item>-->


              </el-form>
            </div>

            <div style="width: 50%;">
              <el-form label-width="120px" :model="dataSourceTo" ref="dataSourceTo">
                <el-form-item label="数据源">
                  <el-select filterable style="width: 32%" size="mini" @change="dataToChange()"
                             v-model="dataSourceTo.dataSource"
                             placeholder="数据源">
                    <el-option
                      v-for="item in dataSourceOptions"
                      :key="item.id"
                      :label="item.datasourceName"
                      :value="item.id">
                    </el-option>
                  </el-select>
                  <el-select filterable clearable style="width: 32%;margin-left: 5px" v-if="schemastotag" size="mini"
                             @change="dataToschemaChange()"
                             v-model="dataSourceTo.schema"
                             placeholder="schema">
                    <el-option
                      v-for="(item,index) in schemasToOption"
                      :key="index"
                      :label="item.lable"
                      :value="item.lable">
                    </el-option>
                  </el-select>
                  <el-select filterable style="width: 32%;margin-left: 5px" clearable ref="tableToSelect" size="mini"
                             @change="tableToChange()" v-model="dataSourceTo.dataSourceTable" placeholder="选择表">
                    <el-option
                      v-for="(item,index) in tableToOptions"
                      :key="index"
                      :label="item.lable"
                      :value="item.lable">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="导入前准备语句">
                  <el-input style="width: 91%" type="textarea" size="mini" :rows="4"
                            placeholder="请输入导入数据前执行的sql脚本" v-model="dataSourceTo.targetPreSql"></el-input>
                </el-form-item>
                <el-form-item label="导入后完成语句">
                  <el-input style="width: 91%" type="textarea" size="mini" :rows="4"
                            placeholder="请输入导入数据后执行的sql脚本" v-model="dataSourceTo.targetPostSql"></el-input>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </el-collapse-item>
        <!--       字段映射-->
        <el-collapse-item name="2">
          <template slot="title">
            <svg-icon
              style="width: 120px;height: 30px"
              icon-class="labeltwo" />
          </template>
          <fieldMapping @scrollEvent="scrollEvent" @clearTimer="clearTimer" ref="fieldMapping"></fieldMapping>
        </el-collapse-item>
        <el-collapse-item title="通道控制" name="3">
          <template slot="title">
            <svg-icon
              style="width: 120px;height: 30px"
              icon-class="labelthree" />
          </template>
          <div style="margin-top:10px;display:flex;justify-content:center">
            <div style="width: 60%">
              <el-form :rules="passControlrules" ref="passControl" label-width="130px" :model="passControl">
                <el-form-item label="任务期望最大并发数" prop="threads">
                  <el-input style="width: 60%" size="mini" v-model.number="passControl.threads"
                            autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="错误记录数超过">
               <span style="color: #FFFFFF;font-size: 12px">
                 <el-input style="width: 60%" size="mini"
                           v-model.number="passControl.maxErrorCount"
                           autocomplete="off">
                 </el-input>
                条，任务自动结束</span>
                </el-form-item>
                <el-form-item label="每次读出">
               <span style="color: #FFFFFF;font-size: 12px">
                 <el-input style="width: 60%" size="mini"
                           v-model.number="passControl.fetchSize"
                           autocomplete="off">
                 </el-input>
                行数</span>
                </el-form-item>
                <el-form-item label="每次写入">
               <span style="color: #FFFFFF;font-size: 12px">
                 <el-input style="width: 60%" size="mini"
                           v-model.number="passControl.batchSize"
                           autocomplete="off">
                 </el-input>
                行数</span>
                </el-form-item>
                <el-form-item label="每次写入">
               <span style="color: #FFFFFF;font-size: 12px">
                 <el-input style="width: 60%" size="mini"
                           v-model.number="passControl.batchByteSize"
                           autocomplete="off">
                 </el-input>
                字节数</span>
                </el-form-item>
                <el-form-item label="错误记录数超过">
                 <span style="color: #FFFFFF;font-size: 12px">
                 <el-input style="width: 60%" size="mini"
                           v-model.number="passControl.maxErrorPercent"
                           autocomplete="off">
                 </el-input>
                %，任务自动结束</span>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
  </div>
</template>

<script>
import Print from "@/util/print";
import axios from "axios";
import fieldMapping from "./fieldMapping.vue";
import { debounce } from "../../../util";

export default {
  name: "demo1",
  components: { fieldMapping },
  watch: {
    "passControl.threads"(newval, val) {
      if (newval >= 8) {
        this.abilityDisabled = false;
      } else {
        this.abilityDisabled = true;
      }
    }
  },
  data() {
    return {
      value1: "全部",
      value2: "",
      nodename: {
        nodename: ""
      },
      activeNames: ["1", "3"],
      dataSourceForm: {
        dataSource: "",
        schema: "",
        dataSourceTable: "",
        srcWhereParam: "",
        srcIdExpression: "",
        srcStartId: "",
        srcSqlText: ""
      },
      dataSourceTo: {
        dataSource: "",
        schema: "",
        dataSourceTable: "",
        targetPreSql: "",
        targetPostSql: ""
      },
      dataSourceOptions: [],
      tableOptions: [],
      schemasFromOption: [],
      tableToOptions: [],
      schemasToOption: [],
      passControl: {
        threads: 1,
        maxErrorCount: 0,
        maxErrorPercent: 0,
        ability: false,
        fetchSize: 3000,
        batchSize:3000,
        batchByteSize: 33554432
      },
      abilityDisabled: true,
      schemastotag: false,
      schemasfromtag: false,
      passControlrules: {
        threads: [
          { required: true, message: "并发数不能为空", trigger: "blur" },
          { type: "number", message: "并发数必须为数字值", trigger: "blur" }
        ]
      }

    };
  },
  methods: {
    //反显数据
    invertData(data) {
      if (data) {
        this.dataSourceForm.dataSource = Number(data.srcDatasourceId);
        this.dataSourceForm.dataSourceTable = data.srcTableName;
        this.dataSourceForm.schema = data.srcSchema;
        this.dataSourceForm.srcWhereParam = data.srcWhereParam;
        this.dataSourceForm.src_id_expression = data.src_id_expression;
        this.dataSourceForm.src_start_id = data.src_start_id;
        this.dataSourceForm.srcSqlText = data.srcSqlText;
        this.dataSourceTo.dataSource = Number(data.targetDatasourceId);
        this.dataSourceTo.dataSourceTable = data.targetTableName;
        this.dataSourceTo.schema = data.targetSchema;
        this.dataSourceTo.targetPreSql = data.targetPreSql;
        this.dataSourceTo.targetPostSql = data.targetPostSql;
        this.passControl.maxErrorCount = Number(data.maxErrorCount);
        this.passControl.maxErrorPercent = Number(data.maxErrorPercent);
        this.passControl.threads = Number(data.threads);
        this.dataSourceForm.srcStartId = data.srcStartId;
        this.passControl.fetchSize = Number(data.fetchSize||3000);
        this.passControl.batchSize = Number(data.batchSize||3000);
        this.passControl.batchByteSize = Number(data.batchByteSize||33554432);
        // this.dataSourceForm.srcIdOffset = data.srcIdOffset
        this.dataSourceForm.srcIdExpression = data.srcIdExpression;
        this.dataSourceChange("invert");
        this.dataToChange("invert");
        // this.dataSourceschemaChange("invert")
        // this.dataToschemaChange("invert")
        if (data.srcTableName) {
          Promise.all([this.tableSelectChange(), this.tableToChange(), this.getFormOption()]).then((res) => {
            console.log(res);
            this.$refs.fieldMapping.invertEdges(data.columnList);
          }).finally(() => {

          });
        } else {
          Promise.all([this.sqlgetfield(), this.tableToChange(), this.getFormOption()]).then((res) => {
            console.log(res);
            this.$refs.fieldMapping.invertEdges(data.columnList);
          }).finally(() => {
          });
        }
      }
    },
    getFormOption() {
      return this.$http.post("/offlineSync/findDatasource").then((res) => {
        this.dataSourceOptions = res.data;
      });
    },
    //数据来源  数据源下拉框change事件 tag用于判断是否需要自动打开下拉框
    dataSourceChange(tag) {
      this.tableOptions = [];
      this.schemasFromOption = [];
      let querydata = {
        datasourceId: this.dataSourceForm.dataSource
      };
      this.$http.post("/offlineSync/findTableNames", querydata).then((res) => {
        if (res.data.tables) {
          res.data.tables.forEach((item) => {
            let option = {
              lable: ""
            };
            option.lable = item;
            this.tableOptions.push(option);
          });
        }
        if (res.data.schemas && res.data.schemas.length > 0) {
          this.schemasfromtag = true;
          res.data.schemas.forEach((item) => {
            let option = {
              lable: ""
            };
            option.lable = item;
            this.schemasFromOption.push(option);
          });
        } else {
          this.schemasfromtag = false;
        }
      }).finally(() => {
        if (!tag) {
          this.$nextTick(_ => {
            this.dataSourceForm.dataSourceTable = "";
            this.dataSourceForm.schema = "";
          });
          this.$refs.tableSelect.toggleMenu();

        }
      });
    },
    dataSourceschemaChange(tag) {
      this.tableOptions = [];
      this.schemasFromOption = [];
      let querydata = {
        datasourceId: this.dataSourceForm.dataSource,
        schema: this.dataSourceForm.schema
      };
      this.$http.post("/offlineSync/findTableNames", querydata).then((res) => {
        if (res.data.tables) {
          res.data.tables.forEach((item) => {
            let option = {
              lable: ""
            };
            option.lable = item;
            this.tableOptions.push(option);
          });
        }
        if (res.data.schemas && res.data.schemas.length > 0) {
          this.schemasfromtag = true;
          res.data.schemas.forEach((item) => {
            let option = {
              lable: ""
            };
            option.lable = item;
            this.schemasFromOption.push(option);
          });
        } else {
          this.schemasfromtag = false;
        }

      }).finally(() => {
        if (!tag) {
          this.$nextTick(_ => {
            this.dataSourceForm.dataSourceTable = "";
          });
          this.$refs.tableSelect.toggleMenu();

        }
      });
    },
    // 数据来源 表下拉框change事件
    tableSelectChange() {
      this.$refs.fieldMapping.graph.removeCell(1);
      let querydata = {
        datasourceId: this.dataSourceForm.dataSource,
        tableName: this.dataSourceForm.dataSourceTable,
        schema:this.dataSourceForm.schema
      };
      if (querydata.tableName) {
        return this.$http.post("/dataWork/findColumns", querydata).then((res) => {
          console.log(res);
          this.$refs.fieldMapping.drawSourceTable(res.data);
        }).finally(() => {
          this.activeNames = ["1", "2", "3"];
        });
      }
    },
    //根据sql获取字段
    sqlgetfield() {
      this.$refs.fieldMapping.graph.removeCell(1);
      let querydata = {
        datasourceId: this.dataSourceForm.dataSource,
        srcSqlText: this.dataSourceForm.srcSqlText
      };
      return this.$http.post("/dataWork/findColumns", querydata).then((res) => {
        console.log(res);
        this.$refs.fieldMapping.drawSourceTable(res.data);
      }).finally(() => {
        this.activeNames = ["1", "2", "3"];
      });
    },
    //数据去向 数据源下拉框change事件 tag用于判断是否需要自动打开下拉框
    dataToChange(tag) {
      this.tableToSelect = [];
      this.tableToOptions = [];
      this.schemasToOption = [];
      let querydata = {
        datasourceId: this.dataSourceTo.dataSource
      };
      this.$http.post("/offlineSync/findTableNames", querydata).then((res) => {
        if (res.data.tables) {
          res.data.tables.forEach((item) => {
            let option = {
              lable: ""
            };
            option.lable = item;
            this.tableToOptions.push(option);
          });
        }
        if (res.data.schemas && res.data.schemas.length > 0) {
          this.schemastotag = true;
          res.data.schemas.forEach((item) => {
            let option = {
              lable: ""
            };
            option.lable = item;
            this.schemasToOption.push(option);
          });
        } else {
          this.schemastotag = false;
        }

      }).finally(() => {
        if (!tag) {
          this.$nextTick(_ => {
            this.dataSourceTo.schema = "";
            this.dataSourceTo.dataSourceTable = "";
          });
          this.$refs.tableToSelect.toggleMenu();
        }
      });
    },
    dataToschemaChange(tag) {
      this.tableToSelect = [];
      this.tableToOptions = [];
      this.schemasToOption = [];
      let querydata = {
        datasourceId: this.dataSourceTo.dataSource,
        schema: this.dataSourceTo.schema
      };
      this.$http.post("/offlineSync/findTableNames", querydata).then((res) => {
        if (res.data.tables) {
          res.data.tables.forEach((item) => {
            let option = {
              lable: ""
            };
            option.lable = item;
            this.tableToOptions.push(option);
          });
        }
        if (res.data.schemas && res.data.schemas.length > 0) {
          this.schemastotag = true;
          res.data.schemas.forEach((item) => {
            let option = {
              lable: ""
            };
            option.lable = item;
            this.schemasToOption.push(option);
          });
        } else {
          this.schemastotag = false;
        }

      }).finally(() => {
        if (!tag) {
          this.$nextTick(_ => {
            this.dataSourceTo.dataSourceTable = "";
          });
          this.$refs.tableToSelect.toggleMenu();
        }
      });
    },
    //数据去向 表下拉框change事件
    tableToChange() {
      this.$refs.fieldMapping.graph.removeCell(2);
      let querydata = {
        datasourceId: this.dataSourceTo.dataSource,
        tableName: this.dataSourceTo.dataSourceTable,
        schema:this.dataSourceTo.schema
      };
      return this.$http.post("/dataWork/findColumns", querydata).then((res) => {
        console.log(res);
        this.$refs.fieldMapping.drawToTable(res.data);
      }).finally(() => {
        this.activeNames = ["1", "2", "3"];
      });
    },
    //清空表单
    restForm() {
      // this.$refs.dataSourceForm.resetFields();
      this.dataSourceForm = {
        dataSource: "",
        dataSourceTable: "",
        srcWhereParam: "",
        srcIdExpression: "",
        srcStartId: "",
        srcSqlText: ""
      };
      this.dataSourceTo = {
        dataSource: "",
        dataSourceTable: "",
        targetPreSql: "",
        targetPostSql: ""
      },
        // this.$refs.dataSourceTo.resetFields();
        // this.dataSourceTo = {};
        this.passControl.threads = 1;
      this.passControl.maxErrorCount = 0;
      this.passControl.maxErrorPercent = 0;
      this.passControl.fetchSize = 3000;
      this.passControl.batchSize = 3000;
      this.passControl.batchByteSize = 33554432;
      this.passControl.ability = false;
      this.tableOptions = [];
      this.schemasFromOption = [];
      this.schemasToOption = [];
      this.tableToOptions = [];
      this.activeNames = ["1", "3"];
      this.$refs.fieldMapping.restGraph();
    },
    //清除定时器
    clearTimer() {
      this.isGoing = false;
      clearInterval(this.goingTask);
    },
    //滚动事件
    scroll: debounce(function() {
      console.log(this.$refs.scrolldiv.scrollTop);
      if (this.activeNames.indexOf("1") === -1) {
        this.scrollTop = this.$refs.scrolldiv.scrollTop - 30;
      } else {
        this.scrollTop = this.$refs.scrolldiv.scrollTop - 200;
      }
      console.log(this.scrollTop);

      if (this.scrollTop === 0 || this.$refs.scrolldiv.scrollTop === this.$refs.fieldMapping.graphHeight - 60) {
        this.clearTimer();
      }
    }),
    //滚动事件
    scrollEvent(data) {
      if (data.y < this.scrollTop) {
        if (this.$refs.scrolldiv.scrollTop === 0) {
          this.clearTimer();
        } else if (!this.isGoing) {
          this.isGoing = true;
          this.goingTask = setInterval(_ => {
            this.$refs.scrolldiv.scrollTop -= 10;
            if (this.activeNames.indexOf("1") === -1) {
              this.scrollTop = this.$refs.scrolldiv.scrollTop - 30;
            } else {
              this.scrollTop = this.$refs.scrolldiv.scrollTop - 200;
            }
            data.cell.target = { x: data.cell.target.x, y: data.cell.target.y - 10 };
          }, 50);
        }
      } else if (data.y - this.scrollTop > this.documentHeight - 260) {
        console.log(this.$refs.scrolldiv.scrollHeight, this.$refs.scrolldiv.scrollTop, this.$refs.scrolldiv.clientHeight, 2222);
        if (this.$refs.scrolldiv.scrollHeight - this.$refs.scrolldiv.scrollTop === this.$refs.scrolldiv.clientHeight) {
          this.clearTimer();
        } else if (!this.isGoing) {
          this.isGoing = true;
          this.goingTask = setInterval(_ => {
            this.$refs.scrolldiv.scrollTop += 10;
            if (this.activeNames.indexOf("1") === -1) {
              this.scrollTop = this.$refs.scrolldiv.scrollTop - 30;
            } else {
              this.scrollTop = this.$refs.scrolldiv.scrollTop - 200;
            }
            data.cell.target = { x: data.cell.target.x, y: data.cell.target.y + 10 };
          }, 50);
        }
      } else {
        this.clearTimer();
      }
    }
  },
  computed: {
    documentHeight() {
      return this.$store.getters.documentHeight;
    },
    lastHeight() {
      return this.documentHeight - 130;
    }
  },
  created() {
  },
  mounted() {
    this.getFormOption();
  }
};
</script>

<style scoped>
</style>
